//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by 张洪毓 on 15/11/8.
//  Copyright © 2015年 张洪毓. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
class HomeTableViewController: BaseTableViewController {
    
    private lazy var statuses = [Status]()
    private let reuseIdentifier = "ReuseIdentifier"
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogin {
            visitorLoginView?.setUIInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        //获取网络数据
        //        loadData { (array) -> () in
        //            if array == nil {
        //                SVProgressHUD.showErrorWithStatus(AppErrorTip)
        //                return
        //            }
        //            self.statuses = array!
        //            self.tableView.reloadData()
        //        }
        
        //获取网络数据
        loadData()
        prepareForTableView()
    }
    
    private func prepareForTableView() {
        
        //设置下拉刷新
        refreshControl = UIRefreshControl()
        //添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        
        //
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: reuseIdentifier)
        //预估行高
        tableView.estimatedRowHeight = 200
        //自动计算行高，必须有一个自上而下的约束，也就是谁要自动计算，就要把谁的上下左右约束补全
        tableView.rowHeight = UITableViewAutomaticDimension
        //设置分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.tableFooterView = indicatorView
    }
    
    //加载微博首页数据
    @objc private func loadData() {
        //如果since_id和max_id都有值，服务器不会返回任何数据
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        if indicatorView.isAnimating() {
            since_id = 0
            max_id = statuses.last?.id ?? 0
        } else {
            max_id = 0
            since_id = statuses.first?.id ?? 0
        }

        //加载数据
        //        StatusListViewModel.loadData { (array) -> () in
//        StatusListViewModel.loadData(since_id: since_id) { (array) -> () in
        StatusListViewModel.loadData(since_id: since_id, max_id: max_id) { (array) -> () in
            
            self.refreshControl?.endRefreshing()
            if array == nil {
                //请求失败
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                //加载数据失败，停止动画
                self.indicatorView.stopAnimating()
                return
            }
            
            if since_id > 0 {
                //下拉刷新，直接追加数据
                self.statuses = array! + self.statuses
            }else if max_id > 0 {
                self.statuses += array!
                self.indicatorView.stopAnimating()
            }else {
                //首次加载
                self.statuses = array!
            }
            
            //刷新表格数据
            self.tableView.reloadData()
        }
    }
    
    private lazy var indicatorView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        return indicator
    }()
    
    //    //加载微博首页数据
    //    private func loadData(finishied: (array: [Status]?) -> ()) {
    //
    //        let AFN = AFHTTPSessionManager()
    //        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
    //        guard let token = UserAccountViewModel().token else {
    //            SVProgressHUD.showErrorWithStatus("您没有登录")
    //            return
    //        }
    //
    //        let parameters = ["access_token": token]
    //        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
    //            guard let dict = result as? [String: AnyObject] else{
    //                finishied(array: nil)
    //                return
    //            }
    //            if let arr = dict["statuses"] as? [[String: AnyObject]] {
    //                var list = [Status]()
    //                for item in arr {
    //                    let status = Status(dict: item)
    ////                    self.statuses.append(status)
    //                    list.append(status)
    //                }
    //                finishied(array: list)
    //            }
    //            }) { (_, error) -> Void in
    //                finishied(array: nil)
    //                print(error)
    //        }
    //    }
}


//MARk:  数据源方法
extension HomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! StatusCell
        cell.status = statuses[indexPath.row]
        //        print(statuses[indexPath.row].retweeted_status?.text)
        
        if indexPath.row == statuses.count - 1 && !indicatorView.isAnimating() {
            print("------------------------->\(indexPath.row)")
            indicatorView.startAnimating()
            loadData()
            print("开始静默加载数据")
        }
        return cell
        
    }
}





